<template>
  <div class="app-container">
    <el-card class="box-card" shadow="never" style="marign-bottom:0px">
      <div class="filter-container">
        <el-row>
          <!-- 渠道类型 -->
          <el-select
            v-model="listQuery.channelTypeId"
            placeholder="渠道类型"
            clearable
            style="width: 180px"
            class="filter-item1"
          >
            <el-option
              v-for="option in channelTypeIdOptions"
              :key="option.key"
              :label="option.label"
              :value="option.value"
            />
          </el-select>a
          <!-- 渠道 -->
          <el-select
            v-model="listQuery.channelId"
            placeholder="渠道"
            clearable
            style="width: 180px"
            class="filter-item1"
          >
           <el-option
              v-for="option in channelIdOptions"
              :key="option.key"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
          <!-- 校区 -->
          <el-select
            v-model="listQuery.orgId"
            placeholder="校区"
            clearable
            style="width: 180px"
            class="filter-item1"
          >
            <el-option
              v-for="option in orgIdOptions"
              :key="option.key"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
          <!-- 科系 -->
          <el-select
            v-model="listQuery.departmentId"
            placeholder="科系"
            clearable
            style="width: 180px"
            class="filter-item1"
          >
            <el-option
              v-for="option in departmentIdOptions"
              :key="option.key"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
          <!-- 课   程 -->
          <el-select
            v-model="listQuery.courseId"
            placeholder="课程"
            clearable
            style="width: 180px"
            class="filter-item1"
          >
<el-option
              v-for="option in courseOptions"
              :key="option.key"
              :label="option.label"
              :value="option.value"
            />          </el-select>
          <el-button
            v-waves
            type="primary"
            icon="el-icon-search"
            @click="handleFilter"
          >{{ $t('table.search') }}</el-button>
          <el-button
            v-waves
            type="primary"
            icon="el-icon-download"
            @click="handleDownload"
          >{{ $t('table.export') }}</el-button>
          <el-button type="text" @click="toggleMoreFilters()">
            {{this.toggleBtnText}}
            <i
              class="el-select__caret el-input__icon el-icon-arrow-up is-reverse"
            ></i>
          </el-button>
        </el-row>

        <el-row :style="displayMoreFilters">
          <!-- 咨询师 -->
          <el-select
            v-model="listQuery.ownerId"
            placeholder="咨询师"
            clearable
            style="width: 180px"
            class="filter-item1"
          >
<el-option
              v-for="option in ownerIdOptions"
              :key="option.key"
              :label="option.label"
              :value="option.value"
            />          </el-select>
          <!-- 线索分类 -->
          <el-select
            v-model="listQuery.clueStatusCode"
            placeholder="线索分类"
            clearable
            style="width: 180px"
            class="filter-item1"
          >
<el-option
              v-for="option in clueStatusCodeOptions"
              :key="option.key"
              :label="option.label"
              :value="option.value"
            />          </el-select>
          <!-- 咨询 日期 -->
          <el-date-picker
            v-model="createTime"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            type="daterange"
            @change="handleCreateTimeChange"
            start-placeholder="咨询开始日期"
            end-placeholder="咨询结束日期"
            range-separator="至"
          ></el-date-picker>
        </el-row>

        <el-row :style="displayMoreFilters">
          <!-- 是否承诺到访-->
          <el-select
            v-model="listQuery.isPromiseVisit"
            placeholder="是否承诺到访"
            clearable
            style="width: 180px"
            class="filter-item1"
          >
<el-option
              v-for="option in isPromiseVisitOptions"
              :key="option.key"
              :label="option.label"
              :value="option.value"
            />          </el-select>
          <!-- 诺到访日期-->
          <el-date-picker
            v-model="promiseVisitDate"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            type="daterange"
            @change="handlePromiseVisitDateChange"
            start-placeholder="诺到访开始"
            end-placeholder="诺到访结"
            range-separator="至"
            style="width:280px"
          ></el-date-picker>
          <!-- 是否到访-->
          <el-select
            v-model="listQuery.isVisit"
            placeholder="是否到访"
            clearable
            style="width: 180px"
            class="filter-item1"
          >
<el-option
              v-for="option in isVisitOptions"
              :key="option.key"
              :label="option.label"
              :value="option.value"
            />          </el-select>
          <!-- 到访日期-->
          <el-date-picker
            v-model="promiseVisitDate"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            type="daterange"
            @change="handleVisitTimeChange"
            start-placeholder="到访开始日期"
            end-placeholder="到访结束日期"
            range-separator="至"
          ></el-date-picker>
          <!-- 姓名-->
          <el-input
            placeholder="姓名"
            v-model="listQuery.customerName"
            style="width: 200px;"
            @keyup.enter.native="handleFilter"
            clearable
          />

          <!--电话 -->
          <el-input
            placeholder="电话"
            v-model="listQuery.customerPhone"
            style="width: 200px;"
            @keyup.enter.native="handleFilter"
            clearable
          />

          <!-- 跟进次数 -->
          <el-input
            placeholder="跟进次数"
            v-model="listQuery.updateCount"
            style="width: 200px;"
            @keyup.enter.native="handleFilter"
            clearable
          />
        </el-row>
      </div>
    </el-card>

    <el-card class="box-card" shadow="never" style="marign-bottom:0px">
      <el-row style="text-align:right;padding-bottom:10px">
        <el-col>
          <el-popover
            ref="popover4"
            placement="right"
            width="400"
            trigger="click"
            style="marign-bottom:10px"
          >
            <el-checkbox-group v-model="checkboxVal">
              <el-row :gutter="10">
                <el-col :span="8">
                  <el-checkbox label="timestamp">创建时间</el-checkbox>
                  <el-checkbox label="type">类型</el-checkbox>
                </el-col>
                <el-col :span="8">
                  <el-checkbox label="author">作者</el-checkbox>
                  <el-checkbox label="reviewer">评论者</el-checkbox>
                </el-col>
                <el-col :span="8">
                  <el-checkbox label="importance">重要性</el-checkbox>
                  <el-checkbox label="pageviews">总页数</el-checkbox>
                </el-col>
                <el-col :span="8">
                  <el-checkbox label="status">状态</el-checkbox>
                </el-col>
              </el-row>
            </el-checkbox-group>
          </el-popover>

          <el-button type="text" v-popover:popover4>
            <svg-icon icon-class="component"/>显示列
          </el-button>
        </el-col>
      </el-row>

      <el-table
        v-loading="listLoading"
        :key="tableKey"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
      >
        <el-table-column :label="$t('table.id')" prop="id" align="center" width="65">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-for="fruit in formThead"
          :key="fruit"
          v-bind:label="fruit | labelFilter "
        >
          <template slot-scope="scope">{{ scope.row[fruit] }}</template>
        </el-table-column>

        <el-table-column
          :label="$t('table.actions')"
          align="center"
          width="230"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <router-link :to="'/clue/edit/'+scope.row.id">
              <el-button type="primary" size="small" icon="el-icon-edit">编辑</el-button>
            </router-link>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item :label="$t('table.type')" prop="type">
          <el-select v-model="temp.type" placeholder="Please select">
            <el-option
              v-for="item in calendarTypeOptions"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.date')" prop="timestamp">
          <el-date-picker
            v-model="temp.timestamp"
            type="datetime"
            placeholder="Please pick a date"
          />
        </el-form-item>
        <el-form-item :label="$t('table.title')" prop="title">
          <el-input v-model="temp.title"/>
        </el-form-item>
        <el-form-item :label="$t('table.status')">
          <el-select v-model="temp.status" placeholder="Please select">
            <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.importance')">
          <el-rate
            v-model="temp.importance"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            :max="3"
            style="margin-top:8px;"
          />
        </el-form-item>
        <el-form-item :label="$t('table.remark')">
          <el-input
            :autosize="{ minRows: 2, maxRows: 4}"
            v-model="temp.remark"
            type="textarea"
            placeholder="Please input"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button
          type="primary"
          @click="dialogStatus==='create'?createData():updateData()"
        >{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel"/>
        <el-table-column prop="pv" label="Pv"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  fetchPv,
  createArticle,
  updateArticle
} from "@/api/article";
import waves from "@/directive/waves"; // Waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

const calendarTypeOptions = [
  { key: "CN", display_name: "China" },
  { key: "US", display_name: "USA" },
  { key: "JP", display_name: "Japan" },
  { key: "EU", display_name: "Eurozone" }
];

// arr to obj ,such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});
const defaultFormThead = [
  "timestamp",
  "type",
  "author",
  "reviewer",
  "importance",
  "pageviews",
  "status"
];
export default {
  name: "ComplexTable",
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        importance: "success",
        draft: "info",
        deleted: "danger"
      };
      return statusMap[status];
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    },
    labelFilter(labelKey) {
      const labelMap = {
        timestamp: "姓名",
        type: "电话",
        author: "线索分类",
        reviewer: "渠道",
        importance: "校区",
        pageviews: "跟进人",
        status: "跟进次数"
      };
      return labelMap[labelKey];
    }
  },
  data() {
    return {
      //下拉框数据模型

      channelTypeIdOptions: [], //渠道类型
      channelIdOptions: [], //渠道
      orgIdOptions: [], //校区
      departmentIdOptions: [], //科系
      courseOptions: [], //课程
      ownerIdOptions: [], //咨询师
      clueStatusCodeOptions: [], //线索 分类
      isPromiseVisitOptions: [], //是否承诺到访
      isVisitOptions: [], //是否到访
      createTime: null,
      promiseVisitDate: null,
      visitTime: null,

      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        //渠道类型
        channelTypeId: "",
        //渠道
        channelId: "",
        //校区
        orgId: "",
        //科系
        departmentId: "",
        //课程
        courseId: "",
        //咨询师
        ownerId: "",
        //线索分类
        clueStatusCode: "",
        //咨询日期

        createTimeStart: "",
        createTimeEnd: "",

        //是否承诺到访
        isPromiseVisit: "",
        //诺到访日期范围

        promiseVisitDateStart: "",
        promiseVisitDateEnd: "",
        //是否到访
        isVisit: "",
        //到访日期

        visitTimeStart: "",
        visitTimeEnd: "",
        //姓名
        customerName: "",
        //电话
        customerPhone: "",
        //跟进次数
        updateCount: ""
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,

      temp: {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        type: "",
        status: "published"
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "Edit",
        create: "Create"
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [
          { required: true, message: "type is required", trigger: "change" }
        ],
        timestamp: [
          {
            type: "date",
            required: true,
            message: "timestamp is required",
            trigger: "change"
          }
        ],
        title: [
          { required: true, message: "title is required", trigger: "blur" }
        ]
      },
      downloadLoading: false,

      //是否展示更多的过滤条件
      displayMoreFilters: "display:none",
      toggleBtnText: "展开",

      //动态表头
      key: 1, // table key
      formTheadOptions: [
        "timestamp",
        "type",
        "author",
        "reviewer",
        "importance",
        "pageviews",
        "status"
      ],
      checkboxVal: defaultFormThead, // checkboxVal
      formThead: defaultFormThead,

      //合并表头
      rowList: [],
      spanArr: [],
      position: 0,
      listData: []
    };
  },
  watch: {
    checkboxVal(valArr) {
      this.formThead = this.formTheadOptions.filter(
        i => valArr.indexOf(i) >= 0
      );
      this.key = this.key + 1; // 为了保证table 每次都会重渲 In order to ensure the table will be re-rendered each time
    }
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items;
        this.total = response.data.total;

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: "操作成功",
        type: "success"
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        status: "published",
        type: ""
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024; // mock a id
          this.temp.author = "vue-element-admin";
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp);
          tempData.timestamp = +new Date(tempData.timestamp); // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v);
                this.list.splice(index, 1, this.temp);
                break;
              }
            }
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    handleDelete(row) {
      this.$notify({
        title: "成功",
        message: "删除成功",
        type: "success",
        duration: 2000
      });
      const index = this.list.indexOf(row);
      this.list.splice(index, 1);
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData;
        this.dialogPvVisible = true;
      });
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = ["timestamp", "title", "type", "importance", "status"];
        const filterVal = [
          "timestamp",
          "title",
          "type",
          "importance",
          "status"
        ];
        const data = this.formatJson(filterVal, this.list);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "table-list"
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    toggleMoreFilters() {
      if (this.displayMoreFilters === "display:none") {
        this.displayMoreFilters = "";
        this.toggleBtnText = "收起";
      } else {
        this.displayMoreFilters = "display:none";
        this.toggleBtnText = "展开";
      }
    },

    //所有的获取下拉框数据方法
    //获取所有校区()
    getOrgIdOptions() {
      fetchOrg().then(response => {
        this.orgIdOptions = response.data;
      });
    },
    //根据校区获取所有渠道(校区ID)
    getChannelOptions(orgId) {
      fetchChannel(orgId).then(response => {
        this.channelIdOptions = response.data;
      });
    },
    //课程（校区Id）
    getCourseOptions(orgId) {
      fetchCourse(orgId).then(response => {
        this.clueCourIdOptions = response.data;
      });
    },
    //老师(课程ID,校区ID)
    getTeahcerOptions(courseId, orgId) {
      fetchTeahcer(courseId, orgId).then(response => {
        this.teacherOptions = response.data;
      });
    },
    //咨询师(校区ID)
    getOwnerOptions(orgId) {
      fetchOwner(orgId).then(response => {
        this.ownerIdOptions = response.data;
      });
    },

    //所有change事件
    //校区变化（重置渠道类型、渠道、科系、课程、咨询师）
    handleOrgIdChange() {


    },
    //渠道类型变化（重置渠道）
    handleChannelTypeIdChange() {},
    //科系变化（重置课程）
    handleDepartmentIdChange() {},

    //咨询日期变化（设置开始日期和结束日期）
    handleCreateTimeChange(t) {
      alert(this.listQuery);
      console.log(this.listQuery.shop); //结果为一个数组，如：["2018-08-04", "2018-08-06"]
    },
    //诺到访日期变化（设置开始日期和结束日期）
    handlePromiseVisitDateChange(t) {
      alert(this.listQuery);
      console.log(this.listQuery.shop); //结果为一个数组，如：["2018-08-04", "2018-08-06"]
    },
    //到访日期变化（设置开始日期和结束日期）
    handleVisitTimeChange(t) {
      alert(this.listQuery);
      console.log(this.listQuery.shop); //结果为一个数组，如：["2018-08-04", "2018-08-06"]
    }
  },
  mounted() {
    this.queryData();
  }
};
</script>
<style >
.app-container {
  background-color: #f3f3f3;
}
.box-card {
  margin-bottom: 20px;
}
.el-card__body {
  padding: 20px;
}
/*-.el-card__header{
  padding:10px 8px;
  font-size: 16px;;
  color: #606266;
}*/
</style>
